package com.yunkeji.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yunkeji.common.core.domain.PageQuery;
import com.yunkeji.common.core.page.TableDataInfo;
import com.yunkeji.common.enums.app.EnableEnum;
import com.yunkeji.common.exception.ServiceException;
import com.yunkeji.dao.domain.sys.Banner;
import com.yunkeji.dao.mapper.sys.BannerMapper;
import com.yunkeji.dao.vo.sys.SysBannerVo;
import com.yunkeji.system.domain.bo.BannerBo;
import com.yunkeji.system.service.IBannerService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Objects;

/**
 * 客户端banner表
 *
 * @author 雷擎宇
 * @date 2024-12-09
 */
@RequiredArgsConstructor
@Service
public class BannerServiceImpl implements IBannerService {

    private final BannerMapper baseMapper;


    @Override
    public TableDataInfo<SysBannerVo> queryPageList(BannerBo bo, PageQuery pageQuery) {
        return TableDataInfo.build(
            (IPage<SysBannerVo>) baseMapper.selectVoPage(
                pageQuery.build(),
                Wrappers.lambdaQuery(Banner.class)
                    .eq(!Objects.isNull(bo.getBranch()), Banner::getBranch, bo.getBranch())
                    .orderByDesc(Banner::getCreateTime)));
    }

    @Override
    public Boolean insertByBo(BannerBo bo) {
        if (Objects.isNull(bo.getBranch())) {
            throw new ServiceException("请选择平台");
        }
        if (StringUtils.isEmpty(bo.getImg())) {
            throw new ServiceException("请上传banner图片");
        }
        if (Objects.isNull(bo.getSort())) {
            bo.setSort(0);
        }
        bo.setEnable(EnableEnum.YES.getCode());
        Banner banner = BeanUtil.toBean(bo, Banner.class);
        baseMapper.insert(banner);
        return null;
    }

    @Override
    public Boolean updateByBo(BannerBo bo) {
        if (Objects.isNull(bo.getId())) {
            throw new ServiceException("请选择要修改的数据进行修改");
        }
        if (Objects.isNull(bo.getBranch())) {
            throw new ServiceException("请选择平台");
        }
        if (StringUtils.isEmpty(bo.getImg())) {
            throw new ServiceException("请上传banner图片");
        }
        Banner banner = BeanUtil.toBean(bo, Banner.class);
        baseMapper.updateById(banner);
        return null;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean disable(Long id) {
        Banner banner = baseMapper.selectById(id);
        banner.setEnable(banner.getEnable().equals(EnableEnum.YES.getCode()) ? EnableEnum.NO.getCode() : EnableEnum.YES.getCode());
        return baseMapper.updateById(banner) > 0;
    }
}
